package com.lxhotel.agentmcp.tool;

import com.lxhotel.agentmcp.context.WebContext;
import com.lxhotel.agentmcp.domain.R;
import com.lxhotel.agentmcp.entity.Hotel;
import com.lxhotel.agentmcp.entity.HotelRoomType;
import com.lxhotel.agentmcp.entity.HotelRoomTypeInventory;
import com.lxhotel.agentmcp.entity.UserBooking;
import com.lxhotel.agentmcp.mapper.HotelMapper;
import com.lxhotel.agentmcp.mapper.HotelRoomTypeInventoryMapper;
import com.lxhotel.agentmcp.mapper.HotelRoomTypeMapper;
import com.lxhotel.agentmcp.mapper.UserBookingMapper;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

import static com.lxhotel.agentmcp.enums.BookingStatusEnum.PAYING;


@Service
public class HotelBookTool {

    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private HotelRoomTypeInventoryMapper hotelRoomTypeInventoryMapper;
    @Autowired
    private HotelRoomTypeMapper hotelRoomTypeMapper;
    @Autowired
    private UserBookingMapper userBookingMapper;

    @Tool(description = "用户根据酒店名称，房型信息，预定日期预定酒店")
    public UserBooking bookRoom(@ToolParam(description = "预定日期") Date bookingDate,
                                @ToolParam(description = "房型名称") String hotelRoomName,
                                @ToolParam(description = "酒店名称") String hotelName) {
        List<Hotel> hotelList = hotelMapper.selectByHotelNameLike(hotelName);
        if (ObjectUtils.isEmpty(hotelList)) {
            throw new IllegalArgumentException("酒店不存在");
        }
        if (hotelList.size() > 1) {
            throw new IllegalArgumentException("查询到多个酒店，请提供更详细的预定酒店信息");
        }
        Hotel hotel = hotelList.get(0);
        HotelRoomType hotelRoomType = hotelRoomTypeMapper.selectRoomTypeByName(hotelRoomName, hotel.getId());
        if (ObjectUtils.isEmpty(hotelRoomType)) {
            throw new IllegalArgumentException("该酒店没有该房型");
        }
        HotelRoomTypeInventory hotelRoomTypeInventory = hotelRoomTypeInventoryMapper.getHotelRoomTypeInventory(hotelRoomType.getId(), bookingDate);
        if (hotelRoomTypeInventory.getNum() == 0) {
            throw new IllegalArgumentException("该房型已无房，请选择别的房型入住!");
        }
        UserBooking userBooking = UserBooking.builder()
                .hotelRoomTypeInventoryId(hotelRoomTypeInventory.getId())
                .userId(WebContext.getUserId())
                .orderNo(System.nanoTime() + "")
                .bookingDate(bookingDate)
                .status(PAYING.getCode())
                .statusValue(PAYING.getMessage())
                .build();
        userBookingMapper.insert(userBooking);
        hotelRoomTypeInventoryMapper.updateInventory(hotelRoomTypeInventory.getId());
        return userBooking;
    }

}
